package main

import (
	"encoding/json"
	"io/ioutil"
	"os"

	"github.com/folk113/aliddns/config"
	"github.com/folk113/aliddns/dns"
)

func initConfig(configfile string) (rev int) {
	data, err := ioutil.ReadFile(configfile)
	if err != nil {
		return -1
	}
	err = json.Unmarshal(data, config.AliAccessConfig)
	if err != nil {
		return -2
	}
	if config.AliAccessConfig.Region == "" ||
		config.AliAccessConfig.AccessKeyID == "" ||
		config.AliAccessConfig.AccessKeySecrete == "" ||
		config.AliAccessConfig.Domain == "" {
		return -3
	}
	return 0
}

func main() {
	path := ""
	if len(os.Args) > 1 {
		path = os.Args[1]
	}
	if path == "" {
		config.Log.Error("config file is empty!")
		return
	}
	if initConfig(path) != 0 {
		config.Log.Error("init config error!")
		return
	}
	ip, err := dns.GetIp()
	if err != nil {
		return
	}
	config.Log.Infof("Get IP address:%s successfully", ip)
	dns.NewDns(config.AliAccessConfig.Domain, ip, config.AliAccessConfig.RRList).Bind()
}
